<template>
  <div>
    <!-- <div class="select">
      <div class="item" v-for="item in yzzdSelect" v-bind:key="item.Id">
        {{ item.TagName }}
      </div>
    </div> -->
    <div class="select">
      <div v-for="item in yzzdSelect" v-bind:key="item.Id" class="itemDiv">
        <div
          class="item"
          v-if="typeof item.type == 'undefined' || item.type != 2"
        >
          {{ item.TagName }}
        </div>
      </div>
    </div>

    <div class="flex">
      <div class="flex-left">
        <div class="navigationBar">
          <label>目录结构</label>
        </div>
        <div class="flex-tree">
          <div
            :class="tableIndex == item.Id ? 'hover tree-item' : 'tree-item'"
            v-for="item in tableList"
            v-bind:key="item.Id"
            @click="tableClick(item)"
          >
            {{ item.FolderName }}
          </div>
        </div>
      </div>
      <div class="flex-right">
        <navigation-bar customTitle="标签">
          <div class="searchContent">
            <el-input
              v-model="tagName"
              placeholder="请输入标签名称"
              size="mini"
              style="width: 150px; margin-right: 10px"
            ></el-input>
            <custom-button
              type="search"
              style="margin-right: 10px"
              @searchClick="searchClick"
            ></custom-button>
            <custom-button
              type="reset"
              style="margin-right: 10px"
              @resetClick="resetClick"
            ></custom-button>
          </div>
        </navigation-bar>
        <!-- <tableHeightIndex
          :dataSource="dataSource"
          :tableColumns="tableColumns"
          :btnList="btnList"
          :pageSize="pageSize"
          :pageCount="pageCount"
          :pageNo="pageNo"
          @pageChange="pageChange"
          @handleSelectionChange="handleSelectionChange"
          :height="curHeight"
          selection
        ></tableHeightIndex> -->

        <singleTable
          :dataSource="dataSource"
          :tableColumns="tableColumns"
          height="400"
          :selectItems="yzzdSelect"
          @singleHandleSelectionChange="singleHandleSelectionChange"
        ></singleTable>

        <!-- selection tableIndex的勾选属性，批量删除时放开，暂未接口 -->
      </div>
    </div>
    <div class="singleBtn">
      <el-button
        size="small"
        type="primary"
        style="margin-right: 10px; color: #fff"
        @click="singleBtnClick"
      >
        <i class="el-icon-check"></i> 勾选确定
      </el-button>
    </div>
  </div>
</template>

<script>
import { tagFolderForm } from "@/assets/form/managementCenter/tagFolderForm";
import { tagManageForm } from "@/assets/form/managementCenter/tagManageForm";
import customButton from "@/components/customComponents/customForm/customButton";
// import tableHeightIndex from "@/components/customComponents/customeTable/tableHeightIndex.vue";
import navigationBar from "@/components/customComponents/managementCenter/navigationBarCustom";
import { AjaxCommon } from "@/libs/apiCommon";
import { PopupCommon } from "@/libs/popupCommon";
import singleTable from "@/components/customComponents/customeTable/singleTable.vue";
export default {
  components: {
    navigationBar,
    customButton,
    // tableHeightIndex,
    singleTable,
  },
  props: ["fileId"],
  data() {
    return {
      inter: null,
      yzzdSelect: [],
      yzzdFixedSelect: [],
      curHeight: 400,
      dialogFolderShow: false,
      tableIndex: "",
      tableList: [
        {
          FolderName: "",
          EnCode: "",
          // 相当于parentId
          LastFolderId: "",
          FullEnCode: "",
          IsDelete: false,
          Id: "",
        },
      ],
      selectItem: [],
      tagName: "",
      // table 相关参数  begin
      dataSource: [],
      tableColumns: [
        {
          prop: "TagName",
          label: "标签名称",
        },
        {
          prop: "Descipt",
          label: "标签说明",
          width: 120,
        },
        // {
        // 	prop: "userage",
        // 	label: "创建时间",
        // },
      ],
      btnList: [],
      pageSize: 20,
      pageCount: 100,
      pageNo: 1,
      // table 相关参数  end

      // 弹窗是否显示
      dialogShow: false,
      // 弹窗标题 (新增修改不同)
      dialogTitle: "",

      // form的配置信息
      formConfig: tagManageForm,
      type: "add",

      formConfigFolder: tagFolderForm,
      typeFolder: "add",
      dialogFolderTitle: "新增目录",
    };
  },
  methods: {
    // 选中行改变事件
    singleHandleSelectionChange(e) {
      // 这里会进多次，其实只需要一定时间内最后一次即可，e为最终选择的行集合
      clearTimeout(this.inter);
      let self = this;
      this.inter = setTimeout(() => {
        console.log(e, "111111111111111111最终");
        // 需要记录新增和删除的，根据左侧
        // TODO...................
        // var oldValue = self.yzzdFixedSelect;
        // dtValue里面的id 相当于 e 里面的 Id
        var dtValue = self.yzzdSelect;
        // currentValue 里面的 FolderID  等于 yzId
        var currentValue = e;
        // 弹窗右侧列表的数据
        var yzzdDatasource = self.dataSource;
        // 当前弹窗里面左侧的目录id
        // var yzId = self.yzId;
        var addList = [];
        var removeList = [];
        var item = null;
        // 当前分类下选中了几项
        if (currentValue && currentValue.length > 0) {
          // 这里也要分新增和删除

          // 原本不存在，表示新增的；
          currentValue.forEach((t) => {
            if (typeof dtValue == "undefined" || dtValue.length == 0) {
              addList.push(t);
            } else {
              item = dtValue.find((b) => b.Id == t.Id);
              if (item == null || typeof item == "undefined") {
                addList.push(t);
              }
            }
          });

          // 原本存在，但是没有返回，表示删除；（这里要区分目录，不是同一个目录的不能删除！！！）
          typeof dtValue != "undefined" &&
            dtValue.length > 0 &&
            dtValue.forEach((t) => {
              if (
                e.find((b) => b.Id == t.Id) == null &&
                yzzdDatasource.find((b) => b.Id == t.Id) != null
              ) {
                removeList.push(t);
              }
            });
        } else {
          if (yzzdDatasource && yzzdDatasource.length > 0) {
            // 记录删除的
            yzzdDatasource.forEach((t) => {
              item = dtValue.find((b) => b.Id == t.Id);
              if (item != null || typeof item != "undefined") {
                removeList.push(t);
              }
            });
          }
        }

        var finallyValue = [];
        if (addList.length > 0 || removeList.length > 0) {
          // 保留小写的id和name以及type:   1：新增  ， 2：删除  ， 0：保持不变的
          typeof dtValue != "undefined" &&
            dtValue.length > 0 &&
            dtValue.map((t) => {
              var isAdd = true;
              // 有的原先为1，新增的
              var type = typeof t.type == "undefined" ? 0 : t.type;
              if (removeList.length > 0) {
                if (removeList.find((b) => b.Id == t.Id) != null) {
                  if (type == 1) {
                    isAdd = false;
                  }
                  type = 2;
                }
              }
              if (isAdd) {
                finallyValue.push({
                  Id: t.Id,
                  TagName: t.TagName,
                  type: type,
                  RelationId: t.RelationId,
                });
              }
            });
          if (addList.length > 0) {
            addList.forEach((t) => {
              finallyValue.push({
                Id: t.Id,
                TagName: t.TagName,
                type: 1,
                RelationId: t.RelationId,
              });
            });
          }

          this.yzzdSelect = finallyValue;
        } else {
          // 处理那种原先存在，后来删除，后来又勾上的情况
          dtValue.forEach((t) => {
            if (typeof t.type != "undefined" && t.type == 2) {
              t.type = 0;
            }
            finallyValue.push({
              Id: t.Id,
              TagName: t.TagName,
              type: typeof t.type != "undefined" ? t.type : 0,
              RelationId: t.RelationId,
            });
          });

          this.yzzdSelect = finallyValue;
        }
        // 上面整这么麻烦，因为后台接口只有新增和删除，没有批量修改，根据最终值去覆盖的操作
        console.log(
          addList,
          removeList,
          dtValue,
          finallyValue,
          "新增和删除......"
        );
      }, 500);
    },
    singleBtnClick() {
      if (this.yzzdSelect.length == 0) {
        PopupCommon.notify("info", "请选择标签");
        return;
      }
      var isTrue = true;
      var msg = "";
      var itemList = [];
      // 后端只提供了绑定接口，没有删除绑定的接口
      this.yzzdSelect.forEach((t) => {
        if (t.type != 2) {
          var params = {
            FileID: this.fileId,
            TagID: t.Id,
          };
          itemList.push(params);
        }
      });
      AjaxCommon("/api/TagRelation", "post", itemList).then((res) => {
        if (res.data.status != 200) {
          isTrue = false;
          msg = res.data.msg;
        }
      });

      setTimeout(() => {
        if (isTrue) {
          PopupCommon.notify("success", "绑定成功");
          this.$emit("success", "");
        } else {
          PopupCommon.notify("error", msg);
        }
      }, 1000);
    },
    tableClick(item) {
      this.tableIndex = item.Id;
      this.initPage();
    },
    handleSelectionChange(d) {
      this.selectItem = d;
    },
    formInputFolderChange(e) {
      console.log(e, "e...................");
    },
    formInputChange(e) {
      // if (e.filedName == "idCard") {
      // 	const data = CardId.getInfoByCardId(e.value)
      // 	if (data) {
      // 		let newData = e.allData
      // 		newData["birthday"] = data.birthday
      // 		newData["sex"] = data.sex
      // 		this.$refs.form.changeFormValue(newData)
      // 	}
      // }
      console.log(e);
    },

    searchClick() {
      this.pageNo = 1;
      this.initPage();
    },
    resetClick() {
      this.tagName = "";
      this.pageNo = 1;
      this.initPage();
    },
    // 分页点击事件
    pageChange(p) {
      this.pageNo = p;
      this.initPage();
    },

    initLeftFolder(callback) {
      let self = this;
      self.tableList = [];
      AjaxCommon("/api/folder?folderType=6", "get", null).then((res) => {
        if (res.data.status == 200) {
          self.tableList = res.data.response;
          if (self.tableList && self.tableList.length > 0) {
            this.tableIndex = self.tableList[0].Id;
            callback();
          } else {
            self.tableIndex = "";
            self.tableList = [];
          }
        } else {
          PopupCommon.notify("error", res.data.msg);
        }
      });
    },

    async initRelation() {
      var fileId = this.fileId;
      console.log(fileId);
      var res = await AjaxCommon(
        `/api/TagRelation?FileID=${fileId}`,
        "get",
        null
      );
      return res.data.response;
    },
    async initRela() {
      // 文件已经关联的标签列表
      var relationList = await this.initRelation();
      this.yzzdFixedSelect = relationList;
      this.yzzdSelect = relationList;
    },
    // 初始化事件
    async initPage() {
      // 差个搜索功能
      let self = this;
      var params = `FolderID=${this.tableIndex}`;
      if (this.tagName) {
        params += "&TagName=" + this.tagName;
      }
      AjaxCommon(`/api/Tag?${params}`, "get", null).then((res) => {
        console.log(res, "res....");
        if (res.data.status == 200) {
          self.dataSource = res.data.response;
        } else {
          PopupCommon.notify("error", res.data.msg);
        }
      });
    },
    async initData() {
      await this.initRela();
      this.initPage();
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.initLeftFolder(() => {
        this.initData();
      });
    });
  },
};
</script>

<style scoped>
.flex {
  display: flex;
  margin-bottom: 20px;
}

.flex .flex-left {
  width: 350px;
  margin-right: 10px;
}

.flex .flex-right {
  flex: 1;
}

.flex .flex-left .navigationBar {
  height: 36px;
  line-height: 36px;
  background-color: #fff;
  margin-top: 10px;
}

.flex .flex-left .flex-tree {
  background-color: #fff;
  margin-top: 10px;
  height: 400px;
  overflow-y: auto;
}

.flex .flex-left .flex-tree .delete {
  color: red;
  float: right;
  margin-top: 9px;
  cursor: pointer;
}
.flex .flex-left .flex-tree .edit {
  color: blue;
  float: right;
  margin-top: 9px;
  cursor: pointer;
  margin-right: 10px;
}

.flex .flex-left .flex-tree .tree-item {
  height: 32px;
  line-height: 32px;
  margin: 5px 10px;
  padding: 0 10px;
  font-size: 14px;
  cursor: pointer;
}
.flex .flex-left .flex-tree .tree-item:hover {
  background-color: #e4f1fe;
}
.flex .flex-left .flex-tree .hover {
  background-color: #e4f1fe;
}

.flex .flex-left .navigationBar label {
  text-align: left;
  font-size: 16px;
  color: #333;
  margin-left: 10px;
}

.flex .flex-left .navigationBar span {
  float: right;
  margin-right: 10px;
  color: #333;
  cursor: pointer;
}

.singleTable {
  margin-bottom: 20px;
}
.singleBtn {
  position: absolute;
  bottom: 8px;
  right: 9px;
}

.select {
  font-size: 14px;
  line-height: 30px;
  padding: 5px 10px;
}

.select .item {
  display: inline-block;
  padding: 0px 10px;
  text-align: center;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  margin-right: 10px;
  margin-bottom: 10px;
}
.singleBtn {
  position: absolute;
  bottom: 8px;
  right: 9px;
}
.itemDiv {
  display: inline-block;
}
</style>
